
from rasterio.enums import Resampling

import rasterio


def gen_internal_overviews(filename, factors):
    with rasterio.open(filename, 'r+') as f:
        f.build_overviews(factors, Resampling.average)
        f.update_tags(ns = 'rio_overview', resampling = 'average')


def gen_external_overviews(filename, factors):
    # https://gdal.org/drivers/raster/gtiff.html#configuration-options
    with rasterio.Env(TIFF_USE_OVR=True):
        gen_internal_overviews(filename, factors)


def main(args):
    factors = [2, 4, 8, 16]
    if args.internal:
        gen_internal_overviews(args.src, factors)
    else:
        gen_external_overviews(args.src, factors)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('src')
    parser.add_argument('--internal', action='store_true')
    args = parser.parse_args()
    main(args)
